package fr.pentalog.ctc.controller.page;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ro.peoplecentric.ctc.common.entity.Item;
import ro.peoplecentric.ctc.common.exception.ApplicationException;
import ro.peoplecentric.ctc.common.service.ItemService;
import ro.peoplecentric.ctc.common.util.ui.ItemCriteria;
import fr.pentalog.ctc.util.WebAppConstants;

/**
 * @author Danut Chindris
 * @since September 13, 2013
 */

@Controller
public class ItemsController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public static final String ITEMS_VIEW_NAME = "pages/items";
	public static final String ITEMS_PAGE = "items";

	private static final String SORTING_ORDER = "desc";
	private static final String SORTING_COLUMN = "addedDate";

	@Resource
	private ItemService itemService;

	@RequestMapping(value = { "/items" }, method = RequestMethod.GET)
	public String showItemsPage(Model model, @RequestParam(value = "q", required = false) String q) {
		List<Item> items = null;
		try {
			if (q != null && !q.isEmpty()) {
				ItemCriteria itemCriteria = new ItemCriteria();
				itemCriteria.setSearchValue(q);
				items = itemService.find(itemCriteria);
			}
			else {
				items = itemService.getAllItems(SORTING_ORDER, SORTING_COLUMN);
			}
		}
		catch (ApplicationException e) {
			logger.error(e.getMessage(), e);
		}
		if (items != null && items.size() != WebAppConstants.ZERO) {
			model.addAttribute(WebAppConstants.ARTICLES_ATTRIBUTE, items);
		}
		model.addAttribute(WebAppConstants.ACTIVE_PAGE, ITEMS_PAGE);
		return ITEMS_VIEW_NAME;
	}
}
